from collections import defaultdict

import frappe
from frappe import _, bold
from frappe.model.naming import make_autoname
from frappe.query_builder.functions import CombineDatetime, sum,Timestamp
from frappe.utils import add_days, cint, cstr, flt, get_link_to_form, now, nowtime, today
from pypika import Order
from pypika.terms import ExistsCriterion

from kingdee.stock.deprecated_serial_batch import(
    DeprecatedBatchNoValuation,
    DeprecatedSerialNoValuation,
)
from kingdee.stock.valuation import round_off_if_near_zero


class SerialBatchBundle:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self,key, value)

        self.set_item_details()
        self.process_serial_and_batch_bundle()
        if self.sle.is_cancelled:
            self.delink_serial_and_batch_bundle()

        self.post_process()

    def process_serial_and_batch_bundle(self):
        if self.item_details.has_serial_no:
            self.process_serial_no()
        elif self.item_details.has_batch_no:
            self.process_batch_no()

    def set_item_details(self):
        fields = [
            "has_batch_no",
            "has_serial_no",
            "item_name",
            "item_group",
            "serial_no_series",
            "create_new_batch",
            "batch_number_series",
        ]

        self.item_details = frappe.get_cached_value("Item", self.sle.item_code, fields, as_dict=1)

    def process_serial_no(self):
        if(
            not self.sle.is_cancelled
            and not self.sle.serial_and_batch_bundle
            and self.item_details.has_serial_no == 1
        ):
            self.make_serial_batch_no_bundle()
        elif not self.sle.is_cancelled:
            self.validate_item_and_warehouse()

    def is_material_transfer(self):
        allowed_types = [
            "Material Transfer",
            "Send to Subcontractor",
            "Material Transfer to Manufacture",
        ]

        if(
            self.sle.voucher_type == "Stock Entry"
            and not self.sle.is_cancelled
            and frappe.get_cached_value("Stock Entry", self.sle.voucher_no, "purpose") in allowed_types
        ):
            return True
        
    def make_serial_batch_no_bundle_for_material_transfer(self):
        from kingdee.controllers.stock_controller import make_bundle_for_material_transfer
    
    

